"""
测试SOAP XML报文处理功能，包括在soap:Body中添加自定义命名空间
"""

from com.tools.Xml_Utils.xml_utils import XmlUtils


def test_soap_with_custom_namespace():
    """
    测试SOAP XML报文处理功能
    """
    print("测试SOAP XML报文处理功能:")
    
    # SOAP XML报文
    soap_xml = '''<?xml version="1.0" encoding="UTF-8"?>
        <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
                       xmlns:web="http://www.webserviceX.NET">
            <soap:Header/>
            <soap:Body>
                <web:GetWeather>
                    <web:CityName>Beijing</web:CityName>
                    <web:CountryName>China</web:CountryName>
                </web:GetWeather>
                <web:GetWeatherResponse>
                    <web:GetWeatherResult>
                        <![CDATA[<CurrentWeather><Location>Beijing</Location><Time>2023-01-01 12:00:00</Time><Temperature>10C</Temperature></CurrentWeather>]]>
                    </web:GetWeatherResult>
                </web:GetWeatherResponse>
            </soap:Body>
        </soap:Envelope>'''
    
    print("原始SOAP XML:")
    print(soap_xml)
    
    # 加载XML
    xml_obj = XmlUtils(xml_string=soap_xml)
    
    # 测试命名空间解析
    print("\n测试命名空间解析:")
    namespaces = xml_obj.get_namespaces()
    print(f"解析到的命名空间: {namespaces}")
    
    # 验证关键命名空间
    assert "soap" in namespaces
    assert namespaces["soap"] == "http://schemas.xmlsoap.org/soap/envelope/"
    assert "web" in namespaces
    assert namespaces["web"] == "http://www.webserviceX.NET"
    
    # 测试元素查找
    print("\n测试元素查找:")
    
    # 查找Envelope元素
    envelope = xml_obj.find_element("//soap:Envelope")
    print(f"找到Envelope元素: {envelope is not None}")
    assert envelope is not None
    
    # 查找Header元素
    header = xml_obj.find_element("//soap:Header")
    print(f"找到Header元素: {header is not None}")
    assert header is not None
    
    # 查找Body元素
    body = xml_obj.find_element("//soap:Body")
    print(f"找到Body元素: {body is not None}")
    assert body is not None
    
    # 查找GetWeather元素
    get_weather = xml_obj.find_element("//web:GetWeather")
    print(f"找到GetWeather元素: {get_weather is not None}")
    assert get_weather is not None
    
    # 查找CityName元素
    city_name = xml_obj.get_element_text("//web:CityName")
    print(f"CityName内容: {city_name}")
    assert city_name == "Beijing"
    
    # 查找CountryName元素
    country_name = xml_obj.get_element_text("//web:CountryName")
    print(f"CountryName内容: {country_name}")
    assert country_name == "China"
    
    # 查找GetWeatherResponse元素
    response = xml_obj.find_element("//web:GetWeatherResponse")
    print(f"找到GetWeatherResponse元素: {response is not None}")
    assert response is not None
    
    # 查找GetWeatherResult元素
    result = xml_obj.find_element("//web:GetWeatherResult")
    print(f"找到GetWeatherResult元素: {result is not None}")
    assert result is not None
    
    # 测试CDATA内容处理
    result_text = xml_obj.get_element_text("//web:GetWeatherResult")
    print(f"GetWeatherResult文本内容长度: {len(result_text)}")
    assert "<CurrentWeather>" in result_text
    assert "<Location>Beijing</Location>" in result_text
    assert "<Temperature>10C</Temperature>" in result_text
    
    # 测试元素存在性检查
    print("\n测试元素存在性检查:")
    assert xml_obj.element_exists("//soap:Envelope") == True
    assert xml_obj.element_exists("//soap:Header") == True
    assert xml_obj.element_exists("//soap:Body") == True
    assert xml_obj.element_exists("//web:GetWeather") == True
    assert xml_obj.element_exists("//web:NonExistentElement") == False
    
    # 测试元素计数
    print("\n测试元素计数:")
    envelope_count = xml_obj.get_element_count("//soap:Envelope")
    body_count = xml_obj.get_element_count("//soap:Body")
    get_weather_count = xml_obj.get_element_count("//web:GetWeather")
    
    print(f"Envelope元素数量: {envelope_count}")
    print(f"Body元素数量: {body_count}")
    print(f"GetWeather元素数量: {get_weather_count}")
    
    assert envelope_count == 1
    assert body_count == 1
    assert get_weather_count == 1
    
    # 测试获取所有文本内容
    print("\n测试获取所有文本内容:")
    all_text = xml_obj.get_all_text()
    print(f"所有文本内容长度: {len(all_text)}")
    # 注意：由于lxml的get_all_text实现方式不同，这里不进行精确的文本匹配断言
    
    # 测试在Body中添加自定义命名空间xmlns:test="http://www.baidu.com"
    print("\n测试在Body中添加自定义命名空间:")
    # 使用添加带命名空间的元素的方式来间接添加命名空间声明
    test_element = xml_obj.add_element_with_namespace(
        "//soap:Body",
        "TempElement",
        "test",
        "http://www.baidu.com"
    )
    
    if test_element is not None:
        print("成功添加带命名空间的临时元素")
        # 立即删除临时元素
        parent = test_element.getparent()
        if parent is not None:
            parent.remove(test_element)
            print("已删除临时元素")
    
    # 验证命名空间是否添加成功
    namespaces = xml_obj.get_namespaces()
    print(f"更新后的命名空间: {namespaces}")
    assert "test" in namespaces
    assert namespaces["test"] == "http://www.baidu.com"
    
    # 测试添加带命名空间的元素
    print("\n测试添加带命名空间的元素:")
    test_element = xml_obj.add_element_with_namespace(
        "//soap:Body",
        "TestElement",
        "test",
        "http://www.baidu.com",
        "测试内容",
        {"testAttr": "测试属性"}
    )
    
    if test_element is not None:
        print("成功添加带命名空间的元素")
    else:
        print("添加带命名空间的元素失败")
    
    # 验证添加的元素
    test_element_text = xml_obj.get_element_text(".//test:TestElement")
    test_element_attr = xml_obj.get_element_attribute(".//test:TestElement", "testAttr")
    
    print(f"TestElement文本: {test_element_text}")
    print(f"TestElement属性: {test_element_attr}")
    
    assert test_element_text == "测试内容"
    assert test_element_attr == "测试属性"
    
    # 测试元素修改
    print("\n测试元素修改:")
    xml_obj.set_element_text("//web:CityName", "Shanghai")
    xml_obj.set_element_attribute("//web:GetWeather", "updated", "true")
    
    # 验证修改结果
    new_city = xml_obj.get_element_text("//web:CityName")
    is_updated = xml_obj.get_element_attribute("//web:GetWeather", "updated")
    
    print(f"修改后的城市: {new_city}")
    print(f"更新属性: {is_updated}")
    
    assert new_city == "Shanghai"
    assert is_updated == "true"
    
    # 测试添加新元素
    print("\n测试添加新元素:")
    new_element = xml_obj.add_element(
        "//soap:Body",
        "NewElement",
        "新元素内容",
        {"newAttr": "新属性值"}
    )
    
    if new_element is not None:
        print("成功添加新元素")
    else:
        print("添加新元素失败")
    
    # 验证新元素
    new_element_text = xml_obj.get_element_text(".//NewElement")
    new_element_attr = xml_obj.get_element_attribute(".//NewElement", "newAttr")
    
    print(f"新元素文本: {new_element_text}")
    print(f"新元素属性: {new_element_attr}")
    
    assert new_element_text == "新元素内容"
    assert new_element_attr == "新属性值"
    
    # 测试删除元素
    print("\n测试删除元素:")
    delete_result = xml_obj.remove_element(".//NewElement")
    print(f"删除元素结果: {delete_result}")
    assert delete_result == True
    
    # 验证元素是否已删除
    exists = xml_obj.element_exists(".//NewElement")
    print(f"新元素是否还存在: {exists}")
    assert exists == False
    
    # 测试转换为字符串
    print("\n测试转换为字符串:")
    xml_string = xml_obj.to_string(pretty_print=True)
    print("XML字符串长度:", len(xml_string))
    
    # 验证关键内容在字符串中
    assert "Shanghai" in xml_string
    assert "测试内容" in xml_string
    assert "测试属性" in xml_string
    
    print("\n所有SOAP XML处理功能测试通过!")


def test_advanced_soap_operations():
    """
    测试高级SOAP操作
    """
    print("\n\n测试高级SOAP操作:")
    
    # 创建SOAP信封
    print("1. 测试创建SOAP信封:")
    xml_obj = XmlUtils.create_empty_xml()
    xml_obj.create_soap_envelope({
        'web': 'http://www.webserviceX.NET',
        'custom': 'http://custom.namespace.com'
    })
    
    # 验证SOAP结构
    envelope = xml_obj.find_element("//soap:Envelope")
    header = xml_obj.find_element("//soap:Header")
    body = xml_obj.find_element("//soap:Body")
    
    print(f"Envelope存在: {envelope is not None}")
    print(f"Header存在: {header is not None}")
    print(f"Body存在: {body is not None}")
    
    # 测试添加SOAP Header元素
    print("\n2. 测试添加SOAP Header元素:")
    auth_element = xml_obj.add_soap_header_element(
        "Authentication",
        "API_KEY_12345",
        {"type": "apiKey"},
        "http://www.webserviceX.NET"
    )
    
    if auth_element is not None:
        print("成功添加SOAP Header元素")
    else:
        print("添加SOAP Header元素失败")
    
    # 验证Header元素
    auth_text = xml_obj.get_element_text(".//web:Authentication")
    auth_type = xml_obj.get_element_attribute(".//web:Authentication", "type")
    
    print(f"认证文本: {auth_text}")
    print(f"认证类型: {auth_type}")
    
    # 测试添加SOAP Body元素
    print("\n3. 测试添加SOAP Body元素:")
    request_element = xml_obj.add_soap_body_element(
        "GetWeather",
        None,
        {"requestId": "REQ001"},
        "http://www.webserviceX.NET"
    )
    
    if request_element is not None:
        print("成功添加SOAP Body元素")
        
        # 添加请求参数
        city_element = xml_obj.add_element(
            ".//web:GetWeather",
            "CityName",
            "Beijing"
        )
        
        country_element = xml_obj.add_element(
            ".//web:GetWeather",
            "CountryName",
            "China"
        )
        
        print("成功添加请求参数")
    else:
        print("添加SOAP Body元素失败")
    
    # 验证Body元素
    request_id = xml_obj.get_element_attribute(".//web:GetWeather", "requestId")
    city = xml_obj.get_element_text(".//web:GetWeather/CityName")
    country = xml_obj.get_element_text(".//web:GetWeather/CountryName")
    
    print(f"请求ID: {request_id}")
    print(f"城市: {city}")
    print(f"国家: {country}")
    
    # 测试复制元素
    print("\n4. 测试复制元素:")
    copy_result = xml_obj.copy_element(
        ".//web:GetWeather",
        ".//soap:Body",
        "GetWeatherCopy"
    )
    
    print(f"复制元素结果: {copy_result}")
    
    # 测试从字典创建XML
    print("\n5. 测试从字典创建XML:")
    data = {
        "request": {
            "header": {
                "auth": "API_KEY",
                "timestamp": "2023-01-01T12:00:00Z"
            },
            "body": {
                "operation": "GetWeather",
                "parameters": {
                    "city": "Beijing",
                    "country": "China"
                }
            }
        }
    }
    
    xml_obj2 = XmlUtils.from_dict(data, "Envelope")
    print("从字典创建的XML:")
    xml_string = xml_obj2.to_string()
    print(xml_string)
    
    # 验证创建的XML
    assert "GetWeather" in xml_string
    assert "Beijing" in xml_string
    assert "China" in xml_string
    
    print("高级SOAP操作测试通过!")


if __name__ == "__main__":
    test_soap_with_custom_namespace()
    test_advanced_soap_operations()